package com.rephilo.gateway.filter;

import com.rephilo.gateway.feign.UserRemoteService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component
public class LoginFilter implements GlobalFilter, Ordered {

    static List<String> whiteList = new ArrayList<>();

    static {
        whiteList.add("/user/");
        whiteList.add("/code/");
    }

    @Autowired
    private UserRemoteService userRemoteService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        URI uri = exchange.getRequest().getURI();
        String path = uri.getPath();
        for (String whitePath : whiteList) {
            if (path.contains(whitePath)) {
                return chain.filter(exchange);
            }
        }

        HttpCookie httpCookie = exchange.getRequest().getCookies().getFirst("token");
        if (httpCookie != null) {
            String token = httpCookie.getValue();
            String userInfo = userRemoteService.info(token);
            if (StringUtils.isNotBlank(userInfo)) {
                // 合法请求，放行，执行后续的过滤器
                return chain.filter(exchange);
            }
        }

        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
        DataBuffer wrap = exchange.getResponse().bufferFactory().wrap("请登录".getBytes(StandardCharsets.UTF_8));
        return exchange.getResponse().writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
